package com.detector.common;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpConnectUtil {
	private final Logger logger = LoggerFactory.getLogger(HttpConnectUtil.class);
	/**
	 * get方式
	 * 
	 * @param url
	 * @author
	 * @return
	 */
	public static String readContentFromGet(String urls,String primaryUrl) throws IOException {
		// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
		String GET_URL = PropertiesUtilNew.getValue(primaryUrl);
		String getURL = GET_URL + urls;
		System.out.println("----------------");
		System.out.println(getURL);
		URL url;
		url = new URL(getURL);
		StringBuffer buffer = new StringBuffer();
		try {
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			httpConn.disconnect();
			System.out.println(buffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	public static String readContentFromGet(String urls, JsonObject jsonStr,String primaryUrl) throws IOException, JSONException {
		// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
		String GET_URL = PropertiesUtilNew.getValue(primaryUrl);
		String getURL = GET_URL + urls;
		System.out.println("----------------");
		System.out.println(getURL);
		URL url;
		url = new URL(getURL);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setConnectTimeout(3000);
		http.setDoInput(true);
		http.setDoOutput(true);
		http.setRequestMethod("POST");
		http.setConnectTimeout(60000);
		http.setReadTimeout(60000);
		http.connect();
		BufferedOutputStream out = new BufferedOutputStream(http.getOutputStream());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", jsonStr);
		System.out.println("------------>output:" + jsonObject.toString());
		out.write(jsonObject.toString().getBytes("UTF-8"));
		out.flush();
		out.close();
		BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream(), "utf-8"));
		String line;
		StringBuffer buffer = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}
		reader.close();
		http.disconnect();
		System.out.println(buffer.toString());
		return buffer.toString();
	}

}